import { DesignTable } from '@amcax/base';
import { useMemo } from 'react';
import { DesignTableColumn, Parameter, RSuiteTableColumn } from './types';

export function useTableConfiguration(
  designTable: DesignTable,
  parameters: Parameter[],
) {
  const columns: RSuiteTableColumn[] = useMemo(() => {
    const indexColumn = {
      title: '序号',
      fixed: 'left',
      width: 60,
      resizable: false,
      dataKey: 'seqNum',
    };
    const designTableColumns = (
      designTable?.labels?.map((label, idx) => ({
        title: label,
        dataKey: `col${idx}`,
      })) || []
    ).filter((_, idx) => !!designTable?.keys?.[idx]);

    if (designTableColumns.length === 0) {
      return [];
    }

    return [indexColumn, ...designTableColumns];
  }, [designTable]);

  const configurationDataSource = useMemo(() => {
    if (columns.length === 0) {
      return [];
    }

    const totalCols = designTable?.labels?.length || 0;
    const data = [];
    for (let i = 0; i < (designTable?.values?.length || 0); i += totalCols) {
      const rowIndex = i / totalCols;
      const rowData = { key: `row-${rowIndex}`, seqNum: rowIndex + 1 };

      for (let j = 0; j < totalCols; j++) {
        rowData[`col${j}`] = designTable?.values?.[i + j];
      }
      data.push(rowData);
    }
    return data;
  }, [designTable, columns]);

  const { linkedColumns, unlinkedColumns } = useMemo(() => {
    const columnsDataSource: DesignTableColumn[] =
      designTable?.keys?.map?.((key, colIdx) => {
        const paramLabel = key
          ? parameters.find((p) => p.key === key)?.label || ''
          : '';
        return {
          key: colIdx,
          column: designTable.labels[colIdx] || '',
          parameterLabel: paramLabel,
        };
      }) || [];

    const linkedColumns = columnsDataSource.filter((col) => col.parameterLabel);
    const unlinkedColumns = columnsDataSource.filter(
      (col) => !col.parameterLabel,
    );

    return { linkedColumns, unlinkedColumns };
  }, [designTable, parameters]);

  return {
    columns,
    configurationDataSource,
    linkedColumns,
    unlinkedColumns,
  };
}
